const { ccclass, property } = cc._decorator;


@ccclass
export default class BattleAwaitBtn extends cc.Component {

    @property([cc.Button])
    buttons: cc.Button[] = [];

    @property(cc.Label)
    info: cc.Label = null;

    @property(cc.Integer)
    time: number = 0;

    countNodes: cc.Node[];

    tempTime: number = 0;

    protected onEnable(): void {
        this.countNodes = this.buttons.map(itme => cc.find("Background/count", itme.node));
        this.countNodes.forEach(itme => {
            itme.on("active-in-hierarchy-changed", this.onCountActiveChanged, this);
        });

        this.buttons.forEach(itme => {
            itme.interactable = false;
            let event = new cc.Component.EventHandler();
            event.target = itme.node;
            event.component = "awaitBtn";
            event.handler = "onClick";
            itme.clickEvents.push(event)
        })

    }

    protected onDisable(): void {
        this.countNodes.forEach(itme => {
            itme.targetOff(this);
        });

        this.buttons.forEach(itme => {
            itme.clickEvents = [];
        });

        this.tempTime = this.time; 
    }

    onCountActiveChanged() {
        let isActive = this.countNodes.find(itme => itme.activeInHierarchy);
        if (isActive) {
            this.tempTime = -Infinity;
            this.countNodes.forEach((itme, index) => {
                this.buttons[index].interactable = itme.activeInHierarchy;
            });
        } else {
            this.tempTime = this.time;
            this.buttons.forEach(itme => {
                itme.interactable = false;
            });
            this.info.node.active = true;
        }
    }

    onClick(event: cc.Event.EventTouch): void {
        // this.tempTime = this.time;
        // event.currentTarget.getComponent(cc.Button).interactable = false;
        // this.info.node.active = true;
    }

    protected update(dt: number): void {
        if (this.tempTime > 0) {
            this.info.node.active = true;
            this.tempTime -= dt;
            this.info.string = "等待" + Math.floor(this.tempTime) + "秒后"

        } else {
            this.info.node.active = false;
            if (this.tempTime == -Infinity) {
                this.countNodes.forEach((itme, index) => {
                    this.buttons[index].interactable = itme.activeInHierarchy;
                });
            } else {
                this.countNodes.forEach((itme, index) => {
                    this.buttons[index].interactable = true;
                });
            }
        }
    }

}
